﻿package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.core.network.safeApiCallVoid
import com.sgcc.nfc.lock.data.local.dao.WarningDao
import com.sgcc.nfc.lock.data.local.mapper.toDomain
import com.sgcc.nfc.lock.data.local.mapper.toEntity
import com.sgcc.nfc.lock.data.remote.api.WarningApi
import com.sgcc.nfc.lock.domain.model.PagedList
import com.sgcc.nfc.lock.domain.model.Warning
import com.sgcc.nfc.lock.domain.repository.WarningRepository
import javax.inject.Inject
import kotlinx.coroutines.flow.first

class WarningRepositoryImpl @Inject constructor(
    private val warningApi: WarningApi,
    private val warningDao: WarningDao
) : WarningRepository {

    override suspend fun getWarnings(
        page: Int,
        pageSize: Int,
        status: Int?,
        type: Int?,
        regionId: Long?
    ): NetworkResult<PagedList<Warning>> {
        val response = safeApiCall {
            warningApi.getWarnings(page, pageSize, status, type, regionId)
        }
        return when (response) {
            is NetworkResult.Success -> {
                val paged = response.data.map { it.toDomain() }
                warningDao.upsertAll(paged.data.map { it.toEntity() })
                NetworkResult.Success(paged)
            }
            is NetworkResult.Error -> {
                val local = warningDao.observeWarnings().first().map { it.toDomain() }
                if (local.isNotEmpty()) {
                    NetworkResult.Success(PagedList(local, 1, local.size.toLong(), local.size.toLong(), 1))
                } else {
                    response
                }
            }
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun getWarningDetail(warningId: Long): NetworkResult<Warning> {
        val response = safeApiCall { warningApi.getWarningDetail(warningId) }
        return when (response) {
            is NetworkResult.Success -> NetworkResult.Success(response.data.toDomain())
            is NetworkResult.Error -> response
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun handleWarning(warningId: Long, remark: String?): NetworkResult<Unit> {
        return safeApiCallVoid { warningApi.handleWarning(warningId, remark) }
    }
}
